import Vue from 'vue'
import Vuex from 'vuex'
import {addCart,initCart} from '@/api/product'

Vue.use(Vuex)

let userInfoStr = localStorage.getItem('my_jd_user_info');
let userInfo = userInfoStr ? JSON.parse(userInfoStr) : {}

export default new Vuex.Store({
  state: {
    userInfo:userInfo,
    goodsList:[],
    cartList:[]
  },
  mutations: {
    initUserInfo(state,option){
      state.userInfo = option
      localStorage.setItem("my_jd_user_info",JSON.stringify(option))
    },
    initGoodsList(state,option){
      option = Object.freeze(option)
      state.goodsList = option
    },
    initCart(state,option){
      state.cartList = option
    },
    addCart(state,option){
      state.cartList.unshift(option)
    },
    removeCart(state,option){
      state.cartList = state.cartList.filter(item=>{
        return item.pid != option
      })
    }
  },
  actions: {
    initCartAsync(store,option){
      initCart().then(data=>{
        console.log(data)
        store.commit('initCart',data.data)
      })
    },
    addCartAsync(store,option){
      addCart({
        pid:option.pid,
        count:option.count
      }).then(data=>{
        console.log(data)
        store.commit('addCart',option)
      })
    },
  },
  modules: {
  }
})
